package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;


public class SimpleRedisLock implements ILock{



    private final String name;

    private final StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX= "lock:";
    private static final String ID_PREFIX= UUID.randomUUID().toString(true) + "_" ;

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unLock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }
    public SimpleRedisLock(String name, StringRedisTemplate redisTemplate) {
        this.name = name;
        this.redisTemplate = redisTemplate;
    }


    @Override
    public boolean tryLock(Long timeoutSec) {

        String id = ID_PREFIX + Thread.currentThread().getId();
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX  + name, id, timeoutSec, TimeUnit.SECONDS));
    }

    @Override
    public void unLock() {
        /*String threadId = ID_PREFIX + Thread.currentThread().getId();
        String id = redisTemplate.opsForValue().get(KEY_PREFIX + name);
        if (threadId.equals(id)) {
            redisTemplate.delete(KEY_PREFIX + name);
        }*/

        //调用lua脚本实现
        redisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX  + name),
                ID_PREFIX + Thread.currentThread().getId());
    }
}
